﻿// Jinx AJAX Framework
// Copyright (C) 2008 Blake Hegerle
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

using Jinx.Models.Sequences;

namespace Jinx.Naming.Paths
{
    public class SequenceElementPathNode : IPathNode
    {
        private readonly uint Index;

        public SequenceElementPathNode(uint Index)
        {
            this.Index = Index;
        }

        #region IPathNode Members

        public string PathElement
        {
            get { return MemberNaming.ModelMemberName(Index); }
        }

        public object Resolve(NamingContext Context, object RelativeTo)
        {
            if (RelativeTo == null)
                throw new CouldNotResolvePath(
                    string.Format("Could not get sequence element with index {0} off a null object", Index));

            var Seq = RelativeTo as IObjectSequence;

            if (Seq == null)
                throw new CouldNotResolvePath(
                    "Could not get a sequence element off of an object that does not implement IObjectSequence");

            return Seq.GetObject(Index);
        }

        public void Update(NamingContext Context, object RelativeTo, object Value)
        {
        }

        public bool EquivalentToMemberName(string MemberName)
        {
            return PathElement.Equals(MemberName);
        }

        #endregion

        #region Overrides

        public override bool Equals(object obj)
        {
            var Node = obj as SequenceElementPathNode;

            if (Node != null)
                return (Node.Index == Index);
            
            return false;
        }

        public override int GetHashCode()
        {
            return Index.GetHashCode();
        }

        public override string ToString()
        {
            return PathElement;
        }

        #endregion
    }
}